import {Component, OnInit} from "@angular/core";
import {LocalDataSource} from "ng2-smart-table";
import {SmartTableData} from "../../@core/data/smart-table";
import {NbDateService, NbDialogService} from "@nebular/theme";
import {ActivatedRoute} from "@angular/router";
import {AdminService} from "../../AdminService";
import {DocService, PowerService} from "../../energy/api";
import {BaseRequest} from "../../utils/BaseRequest";
import {map} from "rxjs/operators";
import {ResponseUnitInfo} from "../../energy/api/model/responseUnitInfo";
import {ResponseElectricConsumptionData} from "../../energy/api/model/responseElectricConsumptionData";
import {ElectricityConsumptionData} from "../../energy/api/model/electricityConsumptionData";

@Component({
  selector: 'ele-history',
  templateUrl: './ele-history.component.html',
  styles: [`
    nb-card {
      transform: translate3d(0, 0, 0);
    }

    .margin {
      margin: 10px;
    }
  `],
})
export class EleHistoryComponent implements OnInit {
  settings = {
    pager: {
      display: true,
      perPage: 20
    },
    hideSubHeader: true,
    actions: {
      columnTitle: '操作',
      add: false,
      delete: false,
      edit: false,
      position: 'right',
    },
    columns: {
      devNo: {
        title: '设备编号',
        type: 'string',
      },
      isPooled: {
        title: '是否公摊',
        type: 'string',
      },
      dataStartTime: {
        title: '起始时间',
        type: 'string',
      },
      dataEndTime: {
        title: '结束时间',
        type: 'string',
      },
      beginMeterReading: {
        title: '起始表值',
        type: 'number',
      },
      endMeterReading: {
        title: '结束表值',
        type: 'number',
      },
      totalConsumption: {
        title: '总计消耗',
        type: 'number',
      },
      phaseCurrentA: {
        title: 'A的相电流',
        type: 'number',
      },
      phaseCurrentB: {
        title: 'B的相电流',
        type: 'number',
      },
      phaseCurrentC: {
        title: 'C的相电流',
        type: 'number',
      },
      phaseVoltageA: {
        title: 'A的相电压',
        type: 'number',
      },
      phaseVoltageB: {
        title: 'B的相电压',
        type: 'number',
      },
      phaseVoltageC: {
        title: 'C的相电压',
        type: 'number',
      },
      phaseActivePowerA: {
        title: 'A的相有功功率',
        type: 'number',
      },
      phaseActivePowerB: {
        title: 'B的相有功功率',
        type: 'number',
      },
      phaseActivePowerC: {
        title: 'C的相有功功率',
        type: 'number',
      },
      phaseReactivePowerA: {
        title: 'A的相无功功率',
        type: 'number',
      },
      phaseReactivePowerB: {
        title: 'B的相无功功率',
        type: 'number',
      },
      phaseReactivePowerC: {
        title: 'C的相无功功率',
        type: 'number',
      },
      powerFactor: {
        title: '功率因数',
        type: 'number',
      },
      totalPositiveMeterReading: {
        title: '正总表码',
        type: 'number',
      },
      tipPositiveMeterReading: {
        title: '正尖表码',
        type: 'number',
      },
      peakPositiveMeterReading: {
        title: '正峰表码',
        type: 'number',
      },
      plainPositiveMeterReading: {
        title: '正平表码',
        type: 'number',
      },
      valleyPositiveMeterReading: {
        title: '正谷表码',
        type: 'number',
      },
      totalReverseMeterReading: {
        title: '负总表码',
        type: 'number',
      },
      tipReverseMeterReading: {
        title: '负尖表码',
        type: 'number',
      },
      peakReverseMeterReading: {
        title: '负峰表码',
        type: 'number',
      },
      plainReverseMeterReading: {
        title: '负平表码',
      },
      valleyReverseMeterReading: {
        title: '负谷表码',
        type: 'number',
      },
      totalPositiveActivePower: {
        title: '总正向有功',
        type: 'number',
      },
      tipPositiveActivePower: {
        title: '正向有功尖',
        type: 'number',
      },
      peakPositiveActivePower: {
        title: '正向有功峰',
        type: 'number',
      },
      plainPositiveActivePower: {
        title: '正向有功平',
        type: 'number',
      },
      valleyPositiveActivePower: {
        title: '正向有功谷',
        type: 'number',
      },
      totalReverseActivePower: {
        title: '反向有功总',
        type: 'number',
      },
      totalReverseReactivePower: {
        title: '反向无功总',
        type: 'number',
      },
      rate: {
        title: '倍率',
        type: 'number',
      },
      extInfo: {
        title: '额外信息',
        type: 'string',
      },
    },
  };
  source: DataDataSource;
  devNo: string = '';
  startTime: Date = new Date();
  endTime: Date = new Date();
  chartOption = {};
  chartTotalConsumption = {};
  chartRe = {};
  constructor(private service: SmartTableData
    , private api: PowerService
    , private dialogService: NbDialogService
    , private route: ActivatedRoute
    , private dateService: NbDateService<Date>
    , private admin: AdminService) {
    this.startTime.setDate(0);
  }

  ngOnInit(): void {
    this.route.paramMap.subscribe(value=>{
      const devNo = value.get('deviceId');
      if (devNo != null) this.devNo = devNo;
      this.source = new DataDataSource(this.api,this.dateService,this.devNo,this.startTime,this.endTime,(data)=>{
        this.chart(data);
        this.totalConsumption(data);
        this.totalReverseActivePower(data);
      });
    });
  }

  filter(){
    this.source.devNo = this.devNo;
    this.source.startTime = this.startTime;
    this.source.endTime = this.endTime;
    this.source.setPage(1);
  }

  chart(value:Array<ElectricityConsumptionData>){
    const data = value.map(v=>{
      return [new Date(v.dataStartTime).getTime(),v.totalPositiveActivePower];
    });
    this.chartOption = {
      tooltip: {
        trigger: 'axis',
        position: function (pt) {
          return [pt[0], '10%'];
        }
      },
      toolbox: {
        feature: {
          dataZoom: {
            yAxisIndex: 'none'
          },
          restore: {},
          saveAsImage: {}
        }
      },
      xAxis: {
        type: 'time',
      },
      yAxis: {
        type: 'value',
        boundaryGap: [0, '100%']
      },
      series: [
        {
          type: 'line',
          smooth: true,
          symbol: 'none',
          sampling: 'average',
          itemStyle: {
            color: 'rgb(255, 70, 131)'
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
              offset: 0,
              color: 'rgb(255, 158, 68)'
            }, {
              offset: 1,
              color: 'rgb(255, 70, 131)'
            }])
          },
          data: data
        }
      ]
    };
  }

  totalConsumption(value:Array<ElectricityConsumptionData>){
    const data = value.map(v=>{
      return [new Date(v.dataStartTime).getTime(),v.totalConsumption];
    });
    this.chartTotalConsumption = {
      tooltip: {
        trigger: 'axis',
        position: function (pt) {
          return [pt[0], '10%'];
        }
      },
      toolbox: {
        feature: {
          dataZoom: {
            yAxisIndex: 'none'
          },
          restore: {},
          saveAsImage: {}
        }
      },
      xAxis: {
        type: 'time',
      },
      yAxis: {
        type: 'value',
        boundaryGap: [0, '100%']
      },
      series: [
        {
          type: 'line',
          smooth: true,
          symbol: 'none',
          sampling: 'average',
          itemStyle: {
            color: 'rgb(255, 70, 131)'
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
              offset: 0,
              color: 'rgb(255, 158, 68)'
            }, {
              offset: 1,
              color: 'rgb(255, 70, 131)'
            }])
          },
          data: data
        }
      ]
    };
  }
  totalReverseActivePower(value:Array<ElectricityConsumptionData>){
    const data = value.map(v=>{
      return [new Date(v.dataStartTime).getTime(),v.totalReverseActivePower];
    });
    this.chartRe = {
      tooltip: {
        trigger: 'axis',
        position: function (pt) {
          return [pt[0], '10%'];
        }
      },
      toolbox: {
        feature: {
          dataZoom: {
            yAxisIndex: 'none'
          },
          restore: {},
          saveAsImage: {}
        }
      },
      xAxis: {
        type: 'time',
      },
      yAxis: {
        type: 'value',
        boundaryGap: [0, '100%']
      },
      series: [
        {
          type: 'line',
          smooth: true,
          symbol: 'none',
          sampling: 'average',
          itemStyle: {
            color: 'rgb(255, 70, 131)'
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
              offset: 0,
              color: 'rgb(255, 158, 68)'
            }, {
              offset: 1,
              color: 'rgb(255, 70, 131)'
            }])
          },
          data: data
        }
      ]
    };
  }
}


export class DataDataSource extends LocalDataSource {
  queryType: string = "1";
  all: number = -1;
  constructor(private api: PowerService, private dateService: NbDateService<Date>
              ,public devNo?:string
              ,public startTime?:Date
              ,public endTime?:Date,private handler?:any) {
    super();
    this.pagingConf['page'] = 1;
    this.pagingConf['perPage'] = 20;
  }

  count(): number {
    return this.all;
  }

  getElements(): Promise<any> {
    const query = {
      pageIndex: (this.pagingConf['page'] - 1) * this.pagingConf['perPage'],
      pageSize: this.pagingConf['perPage'],
      devNo:this.devNo,
      queryType:this.queryType
    };
    if(this.startTime!=null)
      query['startTime'] = this.dateService.format(this.startTime, "yyyyMMdd");
    if(this.endTime!=null)
      query['endTime'] = this.dateService.format(this.endTime, "yyyyMMdd");

    return this.api.requestElectricConsumptionData(new BaseRequest(query)).pipe(map((res:ResponseElectricConsumptionData)=>{
        this.all = res.data.dataCount;
        if(this.handler!=null)  this.handler(res.data.devDetailInfoList);
        return res.data.devDetailInfoList;
    })).toPromise();
  }
}
